<template>
  <div class="employees-container">
    <div class="app-container">
      <page-tools>
        <template #left>
          <span>总共: {{ total }} 条</span>
        </template>
        <template #right>
          <el-button size="small" type="warning" @click="$router.push('/employees/import')">导入 Excel</el-button>
          <el-button size="small" type="danger" @click="hExport">导出 Excel</el-button>
          <el-button size="small" type="primary" @click="showDialog = true">新增员工</el-button>
        </template>
      </page-tools>
      <el-card style="margin-top:20px">
        <el-table border :data="employees">
          <el-table-column label="序号" type="index" />
          <el-table-column label="姓名" prop="username" />
          <el-table-column label="头像">
            <template v-slot="{row}">
              <!-- <img class="avatar" :src="row.staffPhoto" alt=""> -->
              <image-holder class="avatar" :src="row.staffPhoto" />
            </template>
          </el-table-column>
          <el-table-column label="工号" prop="workNumber" />
          <el-table-column label="聘用形式">
            <template v-slot="{row}">
              {{ formatEmployment(row.formOfEmployment) || '未知' }}
            </template>
          </el-table-column>
          <el-table-column label="部门" prop="departmentName" />
          <el-table-column sortable label="入职时间" prop="timeOfEntry">
            <template v-slot="{ row }">
              {{ formData(row.timeOfEntry) }}
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template v-slot="{row}">
              <el-button type="text" size="small" @click="$router.push('/employees/detail/' + row.id)">查看</el-button>
              <!-- <el-button type="text" size="small" @click="$router.push('/employees/detail?id=' + row.id)">查看</el-button> -->
              <!-- <el-button type="text" size="small" @click="$router.push({ path: '/employees/detail', query: { id: row.id } })">查看</el-button> -->
              <!-- <el-button type="text" size="small" @click="$router.push({ name: 'detail', params: { id: row.id } })">查看</el-button> -->
              <el-button type="text" size="small" @click="hAssign(row.id)">分配角色</el-button>
              <el-button type="text" size="small" @click="hDel(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <div style="height: 60px; margin-top: 10px">
          <el-pagination
            :current-page="q.page"
            :page-sizes="[10, 15, 20, 30]"
            :page-size="q.size"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="hSizeChange"
            @current-change="hCurrentChange"
          />
        </div>
      </el-card>
    </div>
    <el-dialog
      title="新增员工"
      width="40%"
      :visible.sync="showDialog"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      @close="hClose"
    >
      <emp-dialog ref="empDialog" @close="showDialog = false" @success="hSuccess" />
    </el-dialog>
    <el-dialog
      title="分配角色"
      width="45%"
      :visible.sync="showDialogRole"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      @closed="$refs.assignRole.restRoleIds()"
    >
      <!-- v-if="showDialogRole" -->
      <assign-role :id="curId" ref="assignRole" @close="showDialogRole = false" />
    </el-dialog>
  </div>
</template>

<script>
import { delEmployee, getEmployees } from '@/api/employees'
import employeesConst from '@/constant/employees'
import EmpDialog from './empDialog.vue'
import AssignRole from './assignRole.vue'
import dayjs from 'dayjs'

const hireTypeMap = {}
employeesConst.hireType.forEach(item => { hireTypeMap[item.id] = item.value })

export default {
  components: {
    EmpDialog, AssignRole
  },
  data() {
    return {
      q: {
        page: 1,
        size: 10
      },
      employees: [],
      total: 0,
      showDialog: false,
      showDialogRole: false,
      curId: ''
    }
  },
  created() {
    this.loadEmployees()
  },
  methods: {
    async loadEmployees() {
      const res = await getEmployees(this.q)
      // console.log(res)
      this.total = res.data.total
      this.employees = res.data.rows
    },
    formatEmployment(code) {
      // const result = employeesConst.hireType.find(item => item.id === code)
      // if (result) {
      //   return result.value
      // } else {
      //   return '未知'
      // }
      return hireTypeMap[code]
    },
    hCurrentChange(page) {
      this.q.page = page
      this.loadEmployees()
    },
    hSizeChange(size) {
      this.q.size = size
      this.loadEmployees()
    },
    async hDel(id) {
      try {
        // 提醒是否删除
        await this.$confirm('确定要删除码？', '提示', { type: 'warning' })
        // 发请求
        const res = await delEmployee(id)
        // 提醒删除成功
        this.$message.success(res.message)
        //
        if (this.employees.length === 1 && this.q.page > 1) {
          this.q.page--
        }
        // 更新列表
        this.loadEmployees()
      } catch (e) {
        // 判断是否点击取消
        if (e === 'cancel') return
        this.$message.error(e.message)
      }
    },
    hSuccess() {
      this.showDialog = false
      this.total++
      this.q.page = Math.ceil(this.total / this.q.size)
      this.loadEmployees()
    },
    formData(date) {
      return dayjs(date).format('YYYY-MM-DD')
    },
    hClose() {
      this.$refs.empDialog.resetForm()
    },
    async hExport() {
      const mapInfo = {
        'id': '编号',
        'password': '密码',
        'username': '姓名',
        'mobile': '手机号',
        'timeOfEntry': '入职日期',
        'formOfEmployment': '聘用形式',
        'correctionTime': '转正日期',
        'workNumber': '工号',
        'departmentName': '部门',
        'staffPhoto': '头像地址'
      }
      const res = await getEmployees(this.q.page, this.total)
      const list = res.data.rows
      // 遍历 list 找到每个元素, 将其属性名转为中文
      // const zhList = list.map(enObj => {
      //   const zhObj = {}
      //   const enKeys = Object.keys(enObj)
      //   enKeys.forEach(enKey => {
      //     const zhKey = mapInfo[enKey]
      //     zhObj[zhKey] = enObj[enKey]
      //   })
      //   return zhObj
      // })
      const first = list[0]
      if (!first) return
      const header = Object.keys(first).map(enKey => {
        return mapInfo[enKey]
      })
      const data = list.map(item => {
        const code = item['formOfEmployment']
        item['formOfEmployment'] = hireTypeMap[code]
        return Object.values(item)
      })
      const excel = await import('@/vendor/Export2Excel')
      excel.export_json_to_excel({
        header,
        data,
        filename: '员工数据'
      })
    },
    hAssign(id) {
      this.curId = id
      this.showDialogRole = true
      this.$nextTick(() => {
        // 调用子组件的 loadRoleIds 方法, 加载数据
        this.$refs.assignRole.loadRoleIds()
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.avatar{
  width: 50px;
  height: 50px;
  border-radius: 50%;
}
.el-pagination{
  display: flex;
  height: 60px;
  justify-content: center;
  align-items: center;
}
</style>
